import {
  addQuestion,
  addRule, getCurrentUser,
  getQuestionList,
  getQuestionTypeList,
  removeRule,
  rule,
  updateRule
} from '@/services/ant-design-pro/api';
import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProDescriptions, ProForm, ProFormItem, ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProFormRadio,
  ProTable,
} from '@ant-design/pro-components';
import '@umijs/max';
import {Button, Drawer, Form, message} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import type {FormValueType} from './components/UpdateForm';
import UpdateForm from './components/UpdateForm';

/**
 * @en-US Add node
 * @zh-CN 新增题目
 * @param fields
 */
const handleAdd = async (fields: API.QuestionAddParams) => {
  const hide = message.loading('正在添加');
  try {
    // 获取当前登录用户id
    const res = await addQuestion({
      ...fields,
      "uploadUserId": 1 // TODO: 动态获取当前登录用户的id
    });
    if (res.code === 200 && res.data?.questionId > 0) {
      hide();
      message.success('新增题目成功!');
      return true;
    } else {
      hide();
      message.error('新增题目失败!请重试');
      return false;
    }

  } catch (error) {
    hide();
    message.error('新增题目失败!请重试');
    return false;
  }
};

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: FormValueType) => {
  const hide = message.loading('Configuring');
  try {
    await updateRule({
      name: fields.name,
      desc: fields.desc,
      key: fields.key,
    });
    hide();
    message.success('Configuration is successful');
    return true;
  } catch (error) {
    hide();
    message.error('Configuration failed, please try again!');
    return false;
  }
};

/**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.RuleListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeRule({
      key: selectedRows.map((row) => row.key),
    });
    hide();
    message.success('Deleted successfully and will refresh soon');
    return true;
  } catch (error) {
    hide();
    message.error('Delete failed, please try again');
    return false;
  }
};
const QuestionTableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.RuleListItem>();
  const [selectedRowsState, setSelectedRows] = useState<API.RuleListItem[]>([]);
  const [data, setData] = useState<API.Question[]>()
  const [form] = Form.useForm()


  // 初始化数据
  const initData = async () => {
    let res = await getQuestionList();
    if (res.code === 200) {
      setData(res.data)
    }
  }

  // 初始化生命周期函数
  useEffect(() => {
    initData()
  }, [])

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const columns: ProColumns<API.RuleListItem>[] = [
    {
      title: '题目 ID',
      dataIndex: 'id',
      tip: 'The Question ID is the unique key',
    },
    {
      title: '题目名称',
      dataIndex: 'questionName',
      valueType: 'textarea',
    },
    {
      title: '题目类型',
      dataIndex: 'questionType',
      renderText: (questionType: API.QuestionType) => {
        return questionType.questionName // questionType.userAccount
      },
    },
    {
      title: '上传用户',
      dataIndex: 'uploadUser',
      renderText: (uploadUser: API.CurrentUserResult) => {
        return uploadUser.userAccount // uploadUser.userAccount
      },
    },
    {
      title: '选项A',
      dataIndex: 'optionA',
      valueType: 'textarea',
    },
    {
      title: '选项B',
      dataIndex: 'optionB',
      valueType: 'textarea',
    },
    {
      title: '选项C',
      dataIndex: 'optionC',
      valueType: 'textarea',
    },
    {
      title: '选项D',
      dataIndex: 'optionD',
      valueType: 'textarea',
    },
    {
      title: '正确答案',
      dataIndex: 'rightAnswer',
      valueType: 'textarea',
    },
    {
      title: '状态',
      dataIndex: 'questionStatus',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '正常',
          status: 'Success',
        },
        1: {
          text: '非法',
          status: 'Error',
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <Button variant="solid" color="cyan" key={"edit"}>
          编辑
        </Button>,
        <Button type="primary" danger key={"delete"}>
          删除
        </Button>,
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.PageParams>
        headerTitle={'查询表格'}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        columns={columns}
        dataSource={data}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
              <span>
                服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.callNo!, 0)} 万
              </span>
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
          <Button type="primary">批量审批</Button>
        </FooterToolbar>
      )}
      <ModalForm
        form={form}
        title={'新建题目'}
        width="400px"
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          const success = await handleAdd(value as API.QuestionAddParams);
          if (success) {
            handleModalOpen(false);
            // 重新加载数据
            initData()
          }
        }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: '规则名称为必填项',
            },
          ]}
          width="md"
          name="questionName"
          label="题目名称"
          tooltip="最大为 256 个字符"
        />
        <ProFormSelect
          label="所属题型"
          name="questionTypeId"
          request={async () => {
            const res = await getQuestionTypeList()
            const questionTypes = []
            for (let i = 0; i < res.data.length; i++) {
              questionTypes.push({
                "label": res.data[i].questionName,
                "value": res.data[i].id
              })
            }
            return questionTypes
          }
          }
          placeholder="请选择所属题型"
          rules={[{ required: true, message: '请选择所属题型!' }]}
        />
        <ProFormItem noStyle shouldUpdate>
          {() => {
            let questionTypeId = form.getFieldValue('questionTypeId')
            if (questionTypeId === 1) {
              // 单选题
              return (
                <>
                  <ProFormText
                    label={"选项A"}
                    name="optionA"
                  >
                  </ProFormText>
                  <ProFormText
                    label={"选项B"}
                    name="optionB"
                  >
                  </ProFormText>
                  <ProFormText
                    label={"选项C"}
                    name="optionC"
                  >
                  </ProFormText>
                  <ProFormText
                    label={"选项D"}
                    name="optionD"
                  >
                  </ProFormText>
                  <ProFormRadio.Group
                    name="rightAnswer"
                    label="正确答案"
                    options={[
                      {
                        label: '选项A',
                        value: 'A',
                      },
                      {
                        label: '选项B',
                        value: 'B',
                      },
                      {
                        label: '选项C',
                        value: 'C',
                      },
                      {
                        label: '选项D',
                        value: 'D',
                      },
                    ]}
                  />
                </>
              )
            }
            else if (questionTypeId === 3) {
              // 判断题
              return (
                <>
                  <ProFormRadio.Group
                    name="rightAnswer"
                    label="正确答案"
                    options={[
                      {
                        label: '正确',
                        value: 'true',
                      },
                      {
                        label: '错误',
                        value: 'false',
                      },
                    ]}
                  />
                </>
              )
            }
            else if (questionTypeId === 6) {
              // 简答题
              return (
                <>
                  <ProFormTextArea
                    name="rightAnswer"
                    label="正确答案"
                  >
                  </ProFormTextArea>
                </>
              )
            }
          }
          }
        </ProFormItem>
      </ModalForm>
      <UpdateForm
        onSubmit={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalOpen(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        updateModalOpen={updateModalOpen}
        values={currentRow || {}}
      />

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};
export default QuestionTableList;
